//冗余 util.js ------------------------
function createDate(time) {
    const now = new Date();
    const year = now.getFullYear();
    const month = (now.getMonth() + 1).toString().padStart(2, '0'); // 月份是从0开始的
    const day = now.getDate().toString().padStart(2, '0');
    return new Date(year, parseInt(month) - 1, parseInt(day), parseInt(time.split(':')[0]), parseInt(time.split(':')[1]), parseInt(time.split(':')[2]));
}

function nano_promise(callback, args = []) {
    return () => {
        return new Promise((resolve, reject) => {
            args.push(resolve, reject)
            callback(...args)
        })
    }
}

async function session_set(key, value, resolve = () => {
}, reject = () => {
}) {
    try {
        if (!key) {
            console.error("session key can't null")
            reject()
            return false
        }
        chrome.storage.local.set({
            [key]: value,
        }, function (res) {
            let error = chrome.runtime.lastError;
            if (error) {
                console.warn(JSON.stringify(error));
                reject(JSON.stringify(error))
            }
            resolve(res)
        })
    } catch (e) {
        reject(e)
    }
}

async function session_set_objects(object, resolve = () => {
}, reject = () => {
}) {
    try {
        if (!object) {
            console.error("session object can't null")
            reject()
            return false
        }
        chrome.storage.local.set(object,
            function (res) {
                resolve(object)
            })
    } catch (e) {
        reject(e)
    }
}

async function session_get(key, default_value = null, resolve = () => {
}, reject = () => {
}) {
    try {
        chrome.storage.local.get({
            [key]: null,
        }, function (res) {
            if (res[key]) {
                resolve(res[key])
            } else {
                resolve(default_value)
            }
        })
    } catch (e) {
        reject(e)
    }
}

async function session_get_objects(items, resolve = () => {
}, reject = () => {
}) {
    try {
        chrome.storage.local.get(items,
            function (res) {
                resolve(res)
            })
    } catch (e) {
        reject(e)
    }
}

async function session_remove(key, resolve = () => {
}, reject = () => {
}) {
    try {
        if (!key) {
            console.error("session key can't null")
            reject()
            return false
        }
        chrome.storage.local.remove(key,
            function (res) {
                resolve(res)
            }
        )
    } catch (e) {
        reject(e)
    }
}

async function session_clear(resolve = () => {
}, reject = () => {
}) {
    try {
        chrome.storage.local.clear(function (res) {
            resolve(res)
        })
    } catch (e) {
        reject(e)
    }
}


let session = {
    get: async function (key, default_value = null) {
        return await nano_promise(session_get, [key, default_value])()
    },
    get_objects: async function (object) {
        return await nano_promise(session_get_objects, [object])()
    },
    set: async function (key, value) {
        return await nano_promise(session_set, [key, value])()
    },
    set_objects: async function (object) {
        return await nano_promise(session_set_objects, [object])()
    },
    remove: async function (key) {
        return await nano_promise(session_remove, [key])()
    },
    clear: async function () {
        return await nano_promise(session_clear)()
    },
}

//冗余 util.js ------------------------


//异步变同步时,保持connect链接存活, 必须return true
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    return true;
});

//接收处理myscript.js、common.js发来的消息, 必须return true
chrome.runtime.onMessage.addListener(async (message, sender, sendResponse) => {
    if (message && message.action == "getCookie") {
        let cookies = await getCookie(message.domain, message.data);
        await session.set("cookies", cookies);
        sendResponse({type: message.action, cookies: cookies});
    }
    if (message && message.action == "delCookie") {
        delCookie(message.domain, message.data);
        sendResponse({type: message.action});
    }
    if (message && message.action == "setCookie") {
        setCookie(message.data)
        sendResponse({type: message.action});
    }
    return true;
});

function getCookie(domain, key) {
    return new Promise((resolve, reject) => {
        chrome.cookies.getAll({domain: domain}, (cookies) => {
            let match = false
            if (!!key) {
                cookies.forEach(item => {
                    if (item.name == key && item.value.length > 0) {
                        match = true
                        let arr = []
                        arr.push(item)
                        resolve(arr)
                    }
                })
            } else {
                match = true
                resolve(cookies)
            }

            if (!match) {
                resolve(null)
            }
        })
    })
}

function delCookie(domain, keys) {
    let url = "https://" + domain.replace(/^\./, "")
    chrome.cookies.getAll({domain: domain}, (cookies) => {
        if (!!keys && keys.length > 0) {
            cookies.forEach(item => {
                if (keys.indexOf(item.name) != -1) {
                    chrome.cookies.remove({url: url, name: item.name}, function (details) {
                        if (details) {
                            console.log('Cookie delete success!');
                        } else {
                            console.error('Cookie not found!');
                        }
                    });
                }
            })
        } else {
            cookies.forEach(item => {
                chrome.cookies.remove({url: url, name: item.name}, function (details) {
                    if (details) {
                        console.log('Cookie delete success!');
                    } else {
                        console.error('Cookie not found!');
                    }
                });
            })
        }
    })
}

function setCookie(arr) {
    for (let obj of arr) {
        let url = "https://" + obj.domain.replace(/^\./, "")
        chrome.cookies.set({url: url, name: obj.name, value: obj.value, path: '/'}, function (details) {
            if (details) {
                console.log('Cookie set success!');
            } else {
                console.error('Cookie not found!');
            }
        });
    }
}

//插件心跳
setInterval(async function () {
    console.log("background heartBeat ...")

    let currentTime = new Date().getTime()
    let endTime = createDate("01:00:00").getTime()
    let startTime = createDate("06:00:00").getTime()
    if (currentTime < startTime && currentTime > endTime) {
        //凌晨1点到6点之间停止刷账号
        await session.set("stopService", true);
        await session.remove("TOKEN_RUNNING");
        await session.remove("current_step");
        await session.remove("current_step_time");
    } else {
        await session.remove("stopService");
    }

    let domain = await session.get("domain", null)
    if (!!domain) {

        let heartBeat_time = await session.get("heartBeat_time", 0)
        let offset = new Date().getTime() - heartBeat_time;

        chrome.tabs.query({}, async function (tabs) {
            for (let i = 0; i < tabs.length; i++) {
                const tab = tabs[i]
                if (tab.url.indexOf(domain) != -1) {

                    //大于5分钟没心跳，页面崩溃
                    if (offset > 60000 * 5) {
                        await session.set("heartBeat_time", new Date().getTime())
                        chrome.tabs.update(tab.id, {url: 'https://www.cma-cgm.com/'});
                        // chrome.tabs.reload(tabs[0].id);
                    }

                    chrome.tabs.sendMessage(tab.id, {
                        type: 'heartBeat'
                    }, function (response) {
                        console.log("heartBeat response: " + JSON.stringify(response))
                    });
                }
            }
        });
    }

}, 5000)

setInterval(async function () {
    let current_step = await session.get("current_step", null)
    let current_step_time = await session.get("current_step_time", 0)
    let domain = await session.get("domain", null)
    if (new Date().getTime() - current_step_time > 120000) {
        chrome.tabs.query({}, async function (tabs) {
            for (let i = 0; i < tabs.length; i++) {
                const tab = tabs[i]
                if (tab.url.indexOf(domain) != -1) {
                    await session.set("current_step_time", new Date().getTime())
                    chrome.tabs.reload(tab.id);
                }
            }
        });
        return;
    }
    if (new Date().getTime() - current_step_time > 60000 && !!!current_step) {
        chrome.tabs.query({}, async function (tabs) {
            for (let i = 0; i < tabs.length; i++) {
                const tab = tabs[i]
                if (tab.url.indexOf(domain) != -1) {
                    chrome.tabs.sendMessage(tab.id, {
                        type: 'getAccount'
                    }, function (response) {
                        console.log("heartBeat response: " + JSON.stringify(response))
                    });
                }
            }
        });
        return;
    }
}, 2000)


chrome.webRequest.onBeforeSendHeaders.addListener(async details => {
    let domain = await session.get("domain", null)
    if (!!details.url && details.url.indexOf("dd.prod.captcha-delivery.com/image") != -1) {
        chrome.tabs.query({}, async function (tabs) {
            for (let i = 0; i < tabs.length; i++) {
                const tab = tabs[i]
                if (tab.url.indexOf(domain) != -1) {
                    chrome.tabs.sendMessage(tab.id, {
                        type: 'image',
                        data: details.url
                    }, function (response) {
                        console.log("image response: " + JSON.stringify(response))
                    });
                }
            }
        });
    }
}, {urls: ["<all_urls>"]}, ['requestHeaders']);